<template>
  <Head title="订单详情" />
  <ShopLayout>
    <div class="bg-gray-100 min-h-screen">
      <div class="max-w-7xl mx-auto px-8 sm:px-16 lg:px-24 py-20">
        <!-- 订单状态 -->
        <div class="bg-white rounded-2xl p-8 shadow-sm mb-6">
          <div class="flex items-center justify-between">
            <div>
              <h1 class="text-2xl font-light text-gray-900 mb-2">订单详情</h1>
              <p class="text-gray-600">订单号：{{ order.order_number }}</p>
            </div>
            <div class="text-right">
              <span
                class="inline-flex items-center px-4 py-2 rounded-full text-lg font-medium"
                :class="getStatusClass(order.status)"
              >
                {{ getStatusText(order.status) }}
              </span>
              <p class="text-sm text-gray-500 mt-2">{{ formatDate(order.created_at) }}</p>
            </div>
          </div>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
          <!-- 左侧：订单信息 -->
          <div class="lg:col-span-2 space-y-6">
            <!-- 商品信息 -->
            <div class="bg-white rounded-2xl p-8 shadow-sm">
              <h2 class="text-xl font-medium text-gray-900 mb-6">商品信息</h2>
              <div class="space-y-4">
                <div
                  v-for="item in order.items"
                  :key="item.id"
                  class="flex gap-4 pb-4 border-b border-gray-200 last:border-0 last:pb-0"
                >
                  <img :src="item.product_image || '/images/placeholder.jpg'" :alt="item.product_name" class="w-24 h-24 object-cover rounded-lg" />
                  <div class="flex-1">
                    <p class="font-medium text-gray-900 text-lg">{{ item.product_name }}</p>
                    <p v-if="item.product_specs && item.product_specs.length > 0" class="text-sm text-gray-500 mt-1">
                      {{ item.product_specs.map(s => `${s.name}: ${s.value}`).join(' · ') }}
                    </p>
                    <div class="flex items-center justify-between mt-3">
                      <span class="text-gray-600">¥{{ (item.price || 0).toLocaleString() }} × {{ item.quantity }}</span>
                      <span class="text-lg font-medium text-gray-900">¥{{ (item.subtotal || 0).toLocaleString() }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 物流信息 -->
            <div v-if="order.status === 'shipped' || order.status === 'delivered'" class="bg-white rounded-2xl p-8 shadow-sm">
              <h2 class="text-xl font-medium text-gray-900 mb-6">物流信息</h2>
              <div class="space-y-3">
                <div class="flex">
                  <span class="text-gray-600 w-24">物流公司：</span>
                  <span class="text-gray-900">{{ order.shipping_company || '-' }}</span>
                </div>
                <div class="flex">
                  <span class="text-gray-600 w-24">物流单号：</span>
                  <span class="text-gray-900 font-mono">{{ order.tracking_number || '-' }}</span>
                </div>
                <div v-if="order.shipped_at" class="flex">
                  <span class="text-gray-600 w-24">发货时间：</span>
                  <span class="text-gray-900">{{ formatDateTime(order.shipped_at) }}</span>
                </div>
                <div v-if="order.shipping_note" class="flex">
                  <span class="text-gray-600 w-24">发货备注：</span>
                  <span class="text-gray-900">{{ order.shipping_note }}</span>
                </div>
              </div>
            </div>

            <!-- 收货信息 -->
            <div class="bg-white rounded-2xl p-8 shadow-sm">
              <h2 class="text-xl font-medium text-gray-900 mb-6">收货信息</h2>
              <div class="space-y-3">
                <div class="flex">
                  <span class="text-gray-600 w-24">收货人：</span>
                  <span class="text-gray-900">{{ order.receiver_name }}</span>
                </div>
                <div class="flex">
                  <span class="text-gray-600 w-24">联系电话：</span>
                  <span class="text-gray-900">{{ order.receiver_phone }}</span>
                </div>
                <div class="flex">
                  <span class="text-gray-600 w-24">收货地址：</span>
                  <span class="text-gray-900">{{ order.receiver_address }}</span>
                </div>
              </div>
            </div>

            <!-- 售后信息 -->
            <div v-if="order.after_sales_requests && order.after_sales_requests.length > 0" class="bg-white rounded-2xl p-8 shadow-sm">
              <h2 class="text-xl font-medium text-gray-900 mb-6">售后信息</h2>
              <div class="space-y-4">
                <div
                  v-for="afterSales in order.after_sales_requests"
                  :key="afterSales.id"
                  class="border border-gray-200 rounded-2xl p-6 hover:shadow-md transition-shadow"
                >
                  <div class="flex items-center justify-between mb-4">
                    <div class="flex items-center gap-4">
                      <span
                        class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium"
                        :class="getAfterSalesStatusClass(afterSales.status)"
                      >
                        {{ getAfterSalesStatusText(afterSales.status) }}
                      </span>
                      <span
                        class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-gray-100 text-gray-700"
                      >
                        {{ getAfterSalesTypeText(afterSales.type) }}
                      </span>
                    </div>
                    <Link
                      :href="route('after-sales.show', afterSales.id)"
                      class="text-sm text-gray-600 hover:text-gray-900 transition-colors"
                    >
                      查看详情 →
                    </Link>
                  </div>
                  
                  <div class="space-y-2">
                    <div class="flex">
                      <span class="text-gray-600 w-20">申请原因：</span>
                      <span class="text-gray-900">{{ afterSales.reason }}</span>
                    </div>
                    <div v-if="afterSales.description" class="flex">
                      <span class="text-gray-600 w-20">详细说明：</span>
                      <span class="text-gray-900">{{ afterSales.description }}</span>
                    </div>
                    <div class="flex">
                      <span class="text-gray-600 w-20">申请时间：</span>
                      <span class="text-gray-900">{{ formatDate(afterSales.created_at) }}</span>
                    </div>
                    <div v-if="afterSales.requested_amount" class="flex">
                      <span class="text-gray-600 w-20">申请金额：</span>
                      <span class="text-gray-900 font-medium">¥{{ (afterSales.requested_amount || 0).toLocaleString() }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 订单备注 -->
            <div v-if="order.notes" class="bg-white rounded-2xl p-8 shadow-sm">
              <h2 class="text-xl font-medium text-gray-900 mb-6">订单备注</h2>
              <p class="text-gray-700">{{ order.notes }}</p>
            </div>
          </div>

          <!-- 右侧：金额信息和操作 -->
          <div class="lg:col-span-1">
            <div class="bg-white rounded-2xl p-6 shadow-sm sticky top-8">
              <h2 class="text-xl font-medium text-gray-900 mb-6">订单金额</h2>
              
              <div class="space-y-3 mb-6">
                <div class="flex justify-between text-sm">
                  <span class="text-gray-600">商品小计</span>
                  <span class="text-gray-900">¥{{ order.subtotal_amount.toLocaleString() }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-gray-600">运费</span>
                  <span class="text-gray-900">
                    <span v-if="order.shipping_fee === 0">免运费</span>
                    <span v-else>¥{{ order.shipping_fee.toLocaleString() }}</span>
                  </span>
                </div>
                <div v-if="order.discount_amount > 0" class="flex justify-between text-sm">
                  <span class="text-gray-600">优惠</span>
                  <span class="text-red-600">-¥{{ order.discount_amount.toLocaleString() }}</span>
                </div>
                <div v-if="order.user_coupon" class="flex justify-between text-sm">
                  <span class="text-gray-600">优惠券</span>
                  <div class="text-right">
                    <span class="text-red-600">-¥{{ (order.user_coupon.discount_amount || 0).toLocaleString() }}</span>
                    <p class="text-xs text-gray-500">{{ order.user_coupon.coupon.name }}</p>
                  </div>
                </div>
                <div class="pt-3 border-t border-gray-200">
                  <div class="flex justify-between items-center">
                    <span class="text-base font-medium text-gray-900">实付金额</span>
                    <span class="text-2xl font-medium text-gray-900">¥{{ order.total_amount.toLocaleString() }}</span>
                  </div>
                </div>
              </div>

              <!-- 支付信息 -->
              <div class="mb-6 pb-6 border-b border-gray-200">
                <div class="flex justify-between text-sm mb-2">
                  <span class="text-gray-600">支付方式</span>
                  <span class="text-gray-900">{{ getPaymentMethodText(order.payment_method) }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-gray-600">支付状态</span>
                  <span class="text-gray-900">{{ getPaymentStatusText(order.payment_status) }}</span>
                </div>
                <div v-if="order.paid_at" class="flex justify-between text-sm mt-2">
                  <span class="text-gray-600">支付时间</span>
                  <span class="text-gray-900">{{ formatDate(order.paid_at) }}</span>
                </div>
              </div>

              <!-- 操作按钮 -->
              <div class="space-y-3">
                <!-- 支付按钮 -->
                <Link
                  v-if="order.status === 'pending' && order.payment_status === 'pending'"
                  :href="route('payment.show', order.order_number)"
                  class="block w-full px-6 py-3 bg-orange-600 text-white rounded-2xl hover:bg-orange-700 transition-colors text-center font-medium"
                >
                  立即支付
                </Link>
                
                <button
                  v-if="canCancel(order)"
                  @click="confirmCancel"
                  class="w-full px-6 py-3 border border-red-300 rounded-2xl text-red-600 hover:bg-red-50 transition-colors"
                >
                  取消订单
                </button>
                <button
                  v-if="canConfirmDelivery(order)"
                  @click="handleConfirmDelivery"
                  class="w-full px-6 py-3 bg-gray-900 text-white rounded-2xl hover:bg-gray-800 transition-colors"
                >
                  确认收货
                </button>
                
                <!-- 售后申请按钮 -->
                <Link
                  v-if="canApplyAfterSales(order) && !hasAfterSalesRequests(order)"
                  :href="route('after-sales.create', { order_number: order.order_number })"
                  class="block w-full px-6 py-3 border border-orange-300 rounded-2xl text-orange-600 hover:bg-orange-50 transition-colors text-center font-medium"
                >
                  申请售后服务
                </Link>
                
                <Link
                  :href="route('orders.index')"
                  class="block w-full px-6 py-3 border border-gray-300 rounded-2xl text-gray-700 hover:bg-gray-50 transition-colors text-center"
                >
                  返回订单列表
                </Link>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 取消订单确认 -->
    <ConfirmDialog
      :show="showCancelDialog"
      type="danger"
      title="确认取消订单"
      :message="`确定要取消订单「${order.order_number}」吗？取消后库存将恢复。`"
      confirm-text="取消订单"
      cancel-text="返回"
      @close="showCancelDialog = false"
      @confirm="handleCancelOrder"
    />
  </ShopLayout>
</template>

<script setup>
import { ref } from 'vue'
import { Head, Link, router } from '@inertiajs/vue3'
import ShopLayout from '@/Layouts/ShopLayout.vue'
import ConfirmDialog from '@/Components/ConfirmDialog.vue'
import { useNotification } from '@/composables/useNotification'

const props = defineProps({
  order: { type: Object, required: true }
})

const { showSuccess, showError } = useNotification()

// 取消订单
const showCancelDialog = ref(false)

const confirmCancel = () => {
  showCancelDialog.value = true
}

const handleCancelOrder = () => {
  router.post(route('order.cancel', props.order.order_number), {
    reason: '用户取消'
  }, {
    onSuccess: () => {
      showSuccess('订单已取消', '')
      showCancelDialog.value = false
    },
    onError: () => {
      showError('取消订单失败', '请重试')
    }
  })
}

// 确认收货
const handleConfirmDelivery = () => {
  router.post(route('order.confirm-delivery', props.order.order_number), {}, {
    onSuccess: () => {
      // 后端已经发送了通知，这里不需要重复显示
    },
    onError: () => {
      showError('确认收货失败', '请重试')
    }
  })
}

// 判断是否可以取消
const canCancel = (order) => {
  return ['pending', 'processing'].includes(order.status)
}

// 判断是否可以确认收货
const canConfirmDelivery = (order) => {
  return order.status === 'shipped'
}

// 判断是否可以申请售后
const canApplyAfterSales = (order) => {
  // 订单必须是已送达状态
  if (order.status !== 'delivered') {
    return false
  }
  
  // 订单必须是已支付状态
  if (order.payment_status !== 'paid') {
    return false
  }
  
  // 检查是否在售后期限内（收货后7天内）
  if (order.delivered_at) {
    const deliveredDate = new Date(order.delivered_at)
    const afterSalesDeadline = new Date(deliveredDate.getTime() + 7 * 24 * 60 * 60 * 1000)
    const now = new Date()
    
    if (now > afterSalesDeadline) {
      return false
    }
  }
  
  return true
}

// 判断是否已有售后申请
const hasAfterSalesRequests = (order) => {
  return order.after_sales_requests && order.after_sales_requests.length > 0
}

// 获取售后状态文本
const getAfterSalesStatusText = (status) => {
  const map = {
    'pending': '待审核',
    'approved': '已通过',
    'rejected': '已拒绝',
    'processing': '处理中',
    'completed': '已完成',
    'cancelled': '已取消'
  }
  return map[status] || status
}

// 获取售后状态样式
const getAfterSalesStatusClass = (status) => {
  const map = {
    'pending': 'bg-yellow-100 text-yellow-700',
    'approved': 'bg-green-100 text-green-700',
    'rejected': 'bg-red-100 text-red-700',
    'processing': 'bg-blue-100 text-blue-700',
    'completed': 'bg-gray-100 text-gray-700',
    'cancelled': 'bg-gray-100 text-gray-700'
  }
  return map[status] || 'bg-gray-100 text-gray-700'
}

// 获取售后类型文本
const getAfterSalesTypeText = (type) => {
  const map = {
    'return': '退货',
    'refund': '退款',
    'exchange': '换货'
  }
  return map[type] || type
}

// 获取状态文本
const getStatusText = (status) => {
  const map = {
    'pending': '待支付',
    'processing': '待发货',
    'shipped': '已发货',
    'delivered': '已送达',
    'cancelled': '已取消'
  }
  return map[status] || status
}

// 获取状态样式
const getStatusClass = (status) => {
  const map = {
    'pending': 'bg-yellow-100 text-yellow-700',
    'processing': 'bg-blue-100 text-blue-700',
    'shipped': 'bg-purple-100 text-purple-700',
    'delivered': 'bg-green-100 text-green-700',
    'cancelled': 'bg-gray-100 text-gray-700'
  }
  return map[status] || 'bg-gray-100 text-gray-700'
}

// 获取支付方式文本
const getPaymentMethodText = (method) => {
  const map = {
    'alipay': '支付宝',
    'wechat': '微信支付',
    'cod': '货到付款'
  }
  return map[method] || method
}

// 获取支付状态文本
const getPaymentStatusText = (status) => {
  const map = {
    'pending': '待支付',
    'paid': '已支付',
    'failed': '支付失败',
    'refunded': '已退款'
  }
  return map[status] || status
}

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 格式化日期时间（带秒）
const formatDateTime = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}
</script>
